'''
Created on Feb 14, 2014

@author: yfrank
'''
import socket

import logging

import threading

import CodingUtils.Logging as Logging

class Channel(object):
    '''
    classdocs
    '''
    buffersize = 1024

    # host is the host address. address is the remote peer
    def __init__(self, host, conn=None,addr=None):
        '''
        Constructor
        '''
        self.lock = threading.Lock()
        self.address = addr # a remote address
        self.host = host # host name
        self.sock = conn # socket


    def close(self):
        self.lock.acquire()
        self.sock.close()
        self.lock.release()

    def read(self):
        self.lock.acquire()
        self.sock.setblocking(0)
        data = ''
        while 1:
            try:
                buff = self.sock.recv(Channel.buffersize)
                data += buff
            except Exception:
                break
        self.sock.setblocking(1)
        self.lock.release()
        return data

    def socket(self):
        return self.sock

    def get_ip(self):
        addr = self.sock.getpeername()
        return addr[0]

    def get_port(self):
        addr = self.sock.getpeername()
        return addr[1]

    def send(self,msg):
        self.lock.acquire()
        bSent = 0
        n = len(msg)
        while bSent < n:
            bSent += self.sock.send(msg[bSent:])
        self.lock.release()

    def open_connection(self,addr,port=0):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.sock.bind((self.host,port))
        except Exception, e: #beware of false error number 10049
            Logging.log(str(e))
        self.sock.connect(addr)
        self.address = addr
        return self.sock


